<template>
  <div>
    <button class="toggle-button" @click="toggleSidebar" title="打开/关闭备注">
      <i class="fas fa-sticky-note"></i>
    </button>

    <div class="sidebar" :style="{ right: sidebarRight }">
      <div class="sidebar-content">
        <div class="notes-container">
          <div v-for="(note, index) in notes" :key="index" class="note-item">
            <span v-if="!note.isEditing" @click="startEditing(index)">{{ note.text }}</span>
            <textarea v-else v-model="note.text" @blur="saveEdit(index)"></textarea>
            <div class="button-container">
              <button @click.stop="deleteNote(index)" title="删除"><i class="fas fa-trash-alt"></i></button>
              <button @click.stop="copyNote(note.text)" title="复制"><i class="fas fa-copy"></i></button>
              <button @click.stop="startEditing(index)" title="编辑"><i class="fas fa-edit"></i></button>
            </div>
          </div>
        </div>
        <div class="input-container">
          <textarea v-model="newNote" class="note-input" placeholder="输入新备注" @blur="saveNewNote"></textarea>
        </div>
      </div>
    </div>
    <div class="copy-success-message" v-show="showCopyMessage">备注已拷贝</div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';

interface Note {
  text: string;
  isEditing: boolean;
}

export default {
  setup() {
    const notes = ref<Note[]>([]);
    const newNote = ref('');
    const sidebarRight = ref('-400px');
    const showCopyMessage = ref(false);
    const currentUrl = ref('');

    const addFontAwesome = () => {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css';
      document.head.appendChild(link);
    };

    const toggleSidebar = () => {
      sidebarRight.value = sidebarRight.value === '0px' ? '-400px' : '0px';
    };

    const loadNotes = () => {
      const savedNotes = JSON.parse(localStorage.getItem(`notes_${currentUrl.value}`) || '[]') as string[];
      notes.value = savedNotes.map((text: string) => ({ text, isEditing: false }));
    };

    const deleteNote = (index: number) => {
      notes.value.splice(index, 1);
      saveNotes();
    };

    const copyNote = (text: string) => {
      navigator.clipboard.writeText(text).then(() => {
        showCopyMessage.value = true;
        setTimeout(() => {
          showCopyMessage.value = false;
        }, 2000);
      }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请重试');
      });
    };

    const startEditing = (index: number) => {
      notes.value[index].isEditing = true;
    };

    const saveEdit = (index: number) => {
      notes.value[index].isEditing = false;
      saveNotes();
    };

    const saveNotes = () => {
      localStorage.setItem(`notes_${currentUrl.value}`, JSON.stringify(notes.value.map(note => note.text)));
    };

    const handleOutsideClick = (event: MouseEvent) => {
      const sidebar = document.querySelector('.sidebar') as HTMLElement;
      const toggleButton = document.querySelector('.toggle-button') as HTMLElement;
      console.log(sidebarRight.value, sidebar, toggleButton);
      if (sidebarRight.value === '0px'
        && sidebar
        && toggleButton
        && !sidebar.contains(event.target as Node)
        && !toggleButton.contains(event.target as Node)) {
        toggleSidebar();
      }
    };

    const saveNewNote = () => {
      if (newNote.value.trim() !== '') {
        notes.value.push({ text: newNote.value, isEditing: false });
        saveNotes();
        newNote.value = '';
      }
    };

    onMounted(() => {
      currentUrl.value = window.location.href;
      loadNotes();
      addFontAwesome();
      document.addEventListener('click', handleOutsideClick);
    });

    onBeforeUnmount(() => {
      document.removeEventListener('click', handleOutsideClick);
    });

    return {
      notes,
      newNote,
      sidebarRight,
      showCopyMessage,
      toggleSidebar,
      saveNewNote,
      deleteNote,
      copyNote,
      startEditing,
      saveEdit
    };
  }
};
</script>

<style scoped>
.toggle-button {
  position: fixed;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  z-index: 10000;
  padding: 10px;
  background-color: transparent; /* 将背景色设置为透明 */
  color: #aab0aa; /* 更改图标颜色，使其在透明背景上更加可见 */
  border: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  transition: color 0.3s ease; /* 添加颜色过渡效果 */
}

.toggle-button:hover {
  color: #aab0aa;/* 鼠标悬停时的颜色变化 */
}

.toggle-button i {
  font-size: 24px; /* 稍微增大图标尺寸 */
}

.sidebar {
  position: fixed;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100%;
  background-color: #f9f9f9;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  transition: right 0.3s;
  z-index: 10000;
  display: flex;
  flex-direction: column;
}

.sidebar-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.notes-container {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.input-container {
  margin-top: auto;
}

.note-input {
  width: 100%;
  height: 100px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 5px;
  resize: vertical;
}

.copy-success-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px;
  background-color: white;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  z-index: 10000;
}

.note-item {
  position: relative;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-container {
  display: flex;
  gap: 5px;
}

.button-container button {
  padding: 5px;
  background-color: transparent;
  border: none;
  cursor: pointer;
}

.button-container button:nth-child(1) {
  color: #f44336;
}

.button-container button:nth-child(2) {
  color: #2196F3;
}

.button-container button:nth-child(3) {
  color: #FFC107;
}
</style>
